import random

from flask import Blueprint, url_for, redirect, render_template
from flask_login import login_required, current_user

from dao import note_dao
from form import forms
from form.forms import EditorForm
from model.note import Note

note_bp = Blueprint("note", __name__)


# 展示出当前用户所有的文章
@note_bp.route('/note/notes', methods=['GET', 'POST'])
@login_required
def list_note():
    style = random.choice(['primary', 'success', 'info', 'warning', 'danger'])
    note_list = note_dao.query_note(current_user.id)
    return render_template("user_page.html", notes=note_list, style=style)


@note_bp.route('/note/update/<int:id>', methods=['GET', 'POST'])
@login_required
def up_note(id):
    note = Note.query.get(id)
    form = EditorForm()
    if form.validate_on_submit():
        title = note.title = form.title.data
        body = note.body = form.body.data
        note_dao.upNote(id, title, body)
        return redirect(url_for('note.list_note'))
    form.title.data = note.title
    form.body.data = note.body
    return render_template('edit.html', form=form, note_id=id)


@note_bp.route('/note/delete/<int:id>', methods=['GET'])
@login_required
def del_note(id):
    note_dao.delete_note(id)
    return redirect(url_for('note.list_note'))


@note_bp.route('/note/editor', methods=['GET', 'POST'])
@login_required
def add_note():
    Editor_Form = forms.EditorForm()
    if Editor_Form.validate_on_submit():
        title = Editor_Form.title.data
        body = Editor_Form.body.data
        user_id = current_user.id
        note_dao.addNote(title, body, user_id)
        return redirect(url_for('note.list_note'))
    else:
        return render_template('ckeditor.html', form=Editor_Form)
